package com.dream.myqiyi;

import java.io.File;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.dream.myqiyi.config.InitializationException;
import com.dream.myqiyi.config.StartupConfig;
import com.dream.myqiyi.db.DBManager;
import com.dream.myqiyi.db.MainDBHelper;
import com.dream.myqiyi.http.NoteSync;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteResourceService;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.service.TagService;
import com.dream.myqiyi.service.impl.NoteManagerImpl;
import com.dream.myqiyi.service.impl.NoteResourceManagerImpl;
import com.dream.myqiyi.service.impl.NoteTagsManagerImpl;
import com.dream.myqiyi.service.impl.NotebookManagerImpl;
import com.dream.myqiyi.service.impl.TagManagerImpl;

import com.dream.myqiyi.Global;

public class MyNeverNote {
	private DBManager 			dbManager;
	private boolean				encryptOnShutdown;			// should I encrypt when I close?
	private boolean				decryptOnShutdown;			// should I decrypt on shutdown;

    //***************************************************************
    //***************************************************************
    //** Constructor & main entry point
    //***************************************************************
    //***************************************************************
    // Application Constructor	
	public MyNeverNote() {
		
		Log.i("[MyNeverNote]", "Starting Application");

		decryptOnShutdown = false;
		encryptOnShutdown = false;

		// Start building the invalid XML tables
				
		// 设置国际化语言 
		
        //* Setup threads & thread timers
//      int indexRunnerCount = Global.getIndexThreads();
//     indexRunnerCount = 1;
		//QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount);	// increase max thread count

		//logger.log(logger.EXTREME, "Building list manager");
        //listManager = new ListManager(dbManager, logger);
        
		//logger.log(logger.EXTREME, "Building index runners & timers");
//        indexRunner = new IndexRunner("indexRunner.log", 
//        		Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
//        		Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
//		indexThread = new QThread(indexRunner, "Index Thread");
//        indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
//        indexRunner.indexImageRecognition = Global.indexImageRecognition();
//        indexRunner.indexNoteBody = Global.indexNoteBody();
//        indexRunner.indexNoteTitle = Global.indexNoteTitle();
//        indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
//		indexThread.start();

	}
	
	boolean initialize(Context context) {
		try {
			checkSDCard();
			
			if (!setupDatabaseConnection()) {
				return false;
			}
			
			initializeService();
			initializeGlobalSettings();
        } catch (InitializationException e) {
            // Fatal
        	Log.e("[MyNeverNote]", e.getMessage());
            e.printStackTrace();
            //QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
            return false;
        }
		return true;
	}
	
	public void shutdown() {
		dbManager.dbShutdown();
	}
	
	private void checkSDCard() {
		// 获取扩展SD卡设备状态  
		String sDStateString = Environment.getExternalStorageState();  		  
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			// 拥有可读可写权限  
			File SDFile = Environment.getExternalStorageDirectory();
			
			Global.noteDir = SDFile.getAbsolutePath() + File.separator + Global.NOTE_DIR;
		} else {
			// SD 卡不可用使用内部数据
			File interalFile = BaseApp.context.getFileStreamPath("temp");
			Global.noteDir = interalFile.getAbsolutePath() + File.separator + Global.NOTE_DIR;
		}
		Global.dbDir = Global.noteDir + File.separator + Global.DB_DIR + File.separator;
		Global.resDir = Global.noteDir + File.separator + Global.IMAGE_DIR + File.separator;
		Global.resDirWeb = "file://" + Global.resDir;

		// 判断文件夹是否存在不存在就创建
		checkPath(Global.noteDir);
		checkPath(Global.dbDir);
		checkPath(Global.resDir);
	}
	
	private void checkPath(String path) {
		File destDir = new File(path);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
	}
	private boolean initializeService() {
		ApplicationContext.getSingleton().addBean("TagManager", new TagManagerImpl(dbManager.getTagDao()));
		ApplicationContext.getSingleton().addBean("NoteManager", new NoteManagerImpl(dbManager.getNoteDao()));
		ApplicationContext.getSingleton().addBean("NotebookManager", new NotebookManagerImpl(dbManager.getNotebookDao()));
		ApplicationContext.getSingleton().addBean("NoteTagsManager", new NoteTagsManagerImpl(dbManager.getNoteTagsDao()));
		ApplicationContext.getSingleton().addBean("NoteResourceManager", new NoteResourceManagerImpl(dbManager.getNoteResourceDao()));
		
		ApplicationContext.getSingleton().addBean("NoteService", new NoteService());
		NotebookService nbSrv = new NotebookService();
		ApplicationContext.getSingleton().addBean("NotebookService", nbSrv);
		ApplicationContext.getSingleton().addBean("TagService", new TagService());
		ApplicationContext.getSingleton().addBean("NoteResourceService", new NoteResourceService());
		
		ApplicationContext.getSingleton().addBean("NoteSync", new NoteSync());

		nbSrv.init();
		return true;
	}
	
	public static void initializeGlobalSettings() throws InitializationException {
		StartupConfig	startupConfig = new StartupConfig();
		Global.noteResServ = (NoteResourceService)ApplicationContext.getSingleton().getBean("NoteResourceService");
		Global.noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		Global.notebookSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		Global.tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");

//        for (String arg : args) {
//            String lower = arg.toLowerCase();
//            if (lower.startsWith("--name="))
//               startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
//            if (lower.startsWith("--home="))
//               startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
//            if (lower.startsWith("--disable-viewing"))
//               startupConfig.setDisableViewing(true);
//            if (lower.startsWith("--sync-only=true"))
//                startupConfig.setSyncOnly(true);
//        }
        //Global.setup(startupConfig);
        
    }

    private boolean setupDatabaseConnection() throws InitializationException {
    	
		dbManager = new DBManager();
		return dbManager.init();
//		if (dbManager.getMainDB() == null) {
//			String msg = new String("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
//					"is accessing the database or NixNote is already running.\n\n" +
//					"Please end any other process or shutdown the other NixNote before starting.\n\nExiting program.");
//				
//	            //QMessageBox.critical(null, tr("Database Connection Error") ,msg);
//				System.exit(16);		
//		}
    }

    // Encrypt the database upon shutdown
    private void encryptOnShutdown() {
    }
    
    // Decrypt the database upon shutdown
    private void decryptOnShutdown() {
    }
    /**
     * Encrypt/Decrypt the local database
     **/
    public void doDatabaseEncrypt() {
        return;
    }
}
